package io.github.lee.jel.ui.main

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.window.OnBackInvokedDispatcher
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.animation.ArgbEvaluatorCompat
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseActivity
import io.github.lee.jel.R
import io.github.lee.jel.databinding.ActivityMainBinding
import io.github.lee.jel.databinding.LayoutMainTabItemBinding

private const val CLICK_TIME_DIFF = 2000L

@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding, MainVM>() {
    private var preClickTime = 0L
    private val pageAdapter by lazy { MainPageAdapter(this@MainActivity) }
    private val mediator by lazy {
        TabLayoutMediator(
            vb?.tlTabs!!, vb?.vpContent!!
        ) { tab, position -> tab.customView = customTabView(position) }
    }

    override fun onCreateViewModel(): MainVM =
        viewModels<MainVM>().value

    private val a by viewModels<MainVM>()

    override fun onCreateSuccess(): ActivityMainBinding =
        ActivityMainBinding.inflate(layoutInflater)

    //===Desc:=============================================================
    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
                clickToExit()
            }
        } else {
            onBackPressedDispatcher.addCallback(this@MainActivity,
                object : OnBackPressedCallback(true) {
                    override fun handleOnBackPressed() {
                        clickToExit()
                    }

                })
        }
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
        vb?.vpContent?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            val selectColor = getColor(R.color.main)
            val normalColor = Color.parseColor("#999999")
            val evaluator = ArgbEvaluatorCompat.getInstance()

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                val currentPosition = vb?.vpContent?.currentItem ?: 0
                if (currentPosition == position) {
                    val currentTab = vb?.tlTabs?.getTabAt(position)?.customView
                    val currentTabImg = currentTab?.findViewById<ImageView>(R.id.ivImg)
                    val currentShowColor = evaluator.evaluate(
                        positionOffset,
                        selectColor, normalColor
                    )
                    currentTabImg?.drawable?.setTint(currentShowColor)

                    val nextTab = vb?.tlTabs?.getTabAt(position + 1)?.customView
                    val nextTabImg = nextTab?.findViewById<ImageView>(R.id.ivImg)
                    val nextShowColor = evaluator.evaluate(
                        positionOffset,
                        normalColor, selectColor
                    )
                    nextTabImg?.drawable?.setTint(nextShowColor)
                } else {
                    val currentTab = vb?.tlTabs?.getTabAt(currentPosition)?.customView
                    val currentTabImg = currentTab?.findViewById<ImageView>(R.id.ivImg)
                    val currentShowColor = evaluator.evaluate(
                        positionOffset,
                        normalColor, selectColor
                    )
                    currentTabImg?.drawable?.setTint(currentShowColor)

                    val nextTab = vb?.tlTabs?.getTabAt(position)?.customView
                    val nextTabImg = nextTab?.findViewById<ImageView>(R.id.ivImg)
                    val nextShowColor = evaluator.evaluate(
                        positionOffset,
                        selectColor, normalColor
                    )
                    nextTabImg?.drawable?.setTint(nextShowColor)
                }
            }
        })

    }

    override fun onSetViewData() {
        super.onSetViewData()
        statusBarColor(Color.TRANSPARENT, true, true)

        vb?.vpContent?.adapter = pageAdapter
        mediator.attach()
    }

    override fun onDestroy() {
        super.onDestroy()
        mediator.detach()
    }

    //===Desc:=============================================================
    private fun customTabView(position: Int): View {
        return LayoutMainTabItemBinding.inflate(layoutInflater)
            .also {
                it.ivImg.setImageDrawable(
                    ContextCompat.getDrawable(
                        mContext, pageAdapter.getIcon(position)
                    )
                )
                if (position == 0) {
                    it.root.isFocusable = true
                    it.root.nextFocusUpId = R.id.vpContent

                }
            }.root
    }

    private fun clickToExit() {
        val now = System.currentTimeMillis()
        if (now - preClickTime > CLICK_TIME_DIFF) {
            toast(getString(R.string.txt_click_exit))
            preClickTime = now
        } else {
            finish()
        }
    }
}